package com.eva.core.job;

import com.eva.config.quartz.JobHandler;
import com.eva.config.quartz.JobHandlerWithDisallowConcurrent;
import com.eva.core.constants.Constants;
import com.eva.core.utils.Utils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 任务调度器代理
 * @author Caesar Liu
 * @date 2022-02-25 10:26
 */
@Slf4j
@Component
public class SchedulerProxy {

    @Autowired
    private Scheduler scheduler;

    /**
     * 创建JOB
     * @param job
     */
    public void createJob (Job job) {
        try {
            // 创建Job
            Class handleClass = JobHandler.class;
            if (job.getDisallowConcurrent()) {
                handleClass = JobHandlerWithDisallowConcurrent.class;
            }
            JobDetail newJob = JobBuilder.newJob(handleClass).withIdentity(job.getHandler()).build();
            // - 添加JOB运行时数据
            newJob.getJobDataMap().put(Constants.Job.JOB_DATA_MAP_JOB_ID, job.getId());
            // 创建Trigger
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression())
                    .withMisfireHandlingInstructionDoNothing();
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(job.getHandler() + "Trigger")
                    .withSchedule(scheduleBuilder).build();
            // 加入调度
            scheduler.scheduleJob(newJob, trigger);
        } catch (SchedulerException e) {
            log.error("EVA: create job throw an exception", e);
        }
    }

    /**
     * JOB代理对象，不依赖其他逻辑层
     */
    @Data
    @AllArgsConstructor
    public static class Job {

        private Integer id;

        private String handler;

        private String cronExpression;

        private Boolean disallowConcurrent;
    }
}
